package com.buding.fx.view;

import com.buding.fx.utils.AuthCodeUtils;
import com.buding.fx.utils.QrCodeUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;




import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author mingdongwei-jwk
 * @date 2022/09/02 15:55
 * @Description
 */

public class LoginPane extends Application {
    private static double dftWeight = 730;
    private static double dftHeight = 500;

    private double leftBoxWeight = 330;
    private GridPane currentGridPane = new GridPane();

    private static double putWeight  = 300;
    private static double putHeight = 30;

    private static String authCode = "";

    private Stage currentStage;


    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage) {

        BorderPane borderPane = new BorderPane();
        VBox leftVbox = new VBox();
        leftVbox.setPrefWidth(leftBoxWeight);
        leftVbox.setPrefHeight(dftHeight);
        Border border = new Border(new BorderStroke(Color.rgb(215,215,215), BorderStrokeStyle.SOLID,null,new BorderWidths(1)));
        leftVbox.setBorder(border);
        creatLeftVbox(leftVbox);

        VBox rightVbox = new VBox();
        rightVbox.setPrefWidth(dftWeight-leftBoxWeight);
        rightVbox.setPrefHeight(dftHeight);
        rightVbox.setAlignment(Pos.TOP_CENTER);
        createRightBox(rightVbox);

        borderPane.setLeft(leftVbox);
        borderPane.setRight(rightVbox);
        borderPane.setStyle("-fx-background-color: white");
        Scene scene = new Scene(borderPane,dftWeight,dftHeight);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
        currentStage = primaryStage;
    }

    private VBox creatLeftVbox(VBox vBox){
        Text text = new Text();
        text.setText("打开知乎APP");
       // text.setFill(Paint.valueOf("15"));
        text.setFont(Font.font("STKaiti",25));
        text.setFill(Color.BLACK);


        Text t2 = new Text();
        t2.setText("在「我的页」左上角打开扫一扫");
        t2.setFont(Font.font(15));
        t2.setFill(Color.rgb(180,180,180));
        VBox.setMargin(t2,new Insets(15,0,0,0));

        //生成二维码
        ImageView imageView = createQrcodeImageView("https://www.zhihu.com/signin");
        imageView.setFitWidth(150);
        imageView.setFitHeight(150);

        Text t3 = new Text("其它扫码方式: 微信");
        t3.setFont(Font.font("KaiTi_GB2312",15));
        t3.setFill(Color.BLACK);

        GridPane gridPane = new GridPane();
        gridPane.setAlignment(Pos.CENTER);
        Button b1 = new Button("下载知乎App");
        Button b2 =new Button("开通机构号");
        Button b3 = new Button("无障碍模式");
        gridPane.add(b1,0,0);
        gridPane.add(b2,1,0);
        gridPane.add(b3,2,0);
        gridPane.setHgap(10);

        vBox.getChildren().addAll(text,t2,imageView,t3,gridPane);

        vBox.setAlignment(Pos.TOP_CENTER);
        VBox.setMargin(text,new Insets(80,0,0,0));
        VBox.setMargin(t3,new Insets(10,0,0,0));
        VBox.setMargin(imageView,new Insets(10,0,0,0));
        VBox.setMargin(gridPane,new Insets(70,0,0,0));
        return vBox;
    }

    private void createRightBox(VBox vbox){
        double weight = 100;
        double height = 50;

        String labStyle = "-fx-text-fill: gray; -fx-font-size: 15";
        String onClickStyle = "-fx-text-fill: black; fx-border-style: medium; -fx-border-width: 0 0 2 0; -fx-border-color: blue; -fx-font-size: 16";
        Label authLabel = new Label("验证码登录");
        authLabel.setPrefWidth(weight);
        authLabel.setPrefHeight(height);
        authLabel.setStyle(labStyle);
        //authLabel
        authLabel.setAlignment(Pos.CENTER);
        Label pwdLabel = new Label("密码登录");
        pwdLabel.setPrefWidth(weight);
        pwdLabel.setPrefHeight(height);
        pwdLabel.setStyle(labStyle);
        pwdLabel.setAlignment(Pos.CENTER);

        HBox hb = new HBox();
        hb.setAlignment(Pos.CENTER_LEFT);
        hb.setPrefWidth(vbox.getPrefWidth());
        hb.setStyle("-fx-font-size: 15; -fx-text-fill: #827e7e");
        hb.setPadding(new Insets(0,0,2,0));
        HBox.setMargin(pwdLabel,new Insets(0,0,0,10));
        MouseEvent mouseEvent = new MouseEvent(MouseEvent.MOUSE_CLICKED, 1,1,1,1, MouseButton.PRIMARY, 1,
                true, true, true, true,
                true, true, true,
                true, true, true, null);

        authLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if (event.getEventType()== MouseEvent.MOUSE_CLICKED){
                    System.out.println("验证码登录事件触发");
                    authLabel.setStyle(onClickStyle);
                    pwdLabel.setStyle(labStyle);
                    createUserAndPwdPane();
                    System.out.println("当前authLabel size: "+   vbox.getChildren().size());
                }
            }
        });
        //默认触发验证码登录效果
        Event.fireEvent(authLabel, mouseEvent);
        pwdLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                System.out.println("账户密码登录事件触发");
                pwdLabel.setStyle(onClickStyle);
                authLabel.setStyle(labStyle);
                createAuthCodePane();
                System.out.println("当前pwdLabel size: "+   vbox.getChildren().size());
            }
        });
        hb.getChildren().addAll(authLabel,pwdLabel);
        currentGridPane.setAlignment(Pos.CENTER_LEFT);
        currentGridPane.setStyle("-fx-font-size: 13; -fx-text-fill: gray");
        currentGridPane.setHgap(5);
        vbox.getChildren().addAll(hb,currentGridPane);
        VBox.setMargin(hb,new Insets(15,20,0,25));
        VBox.setMargin(currentGridPane,new Insets(20,0,0,28));


    }

    public static ImageView createQrcodeImageView(String url){
        ByteArrayOutputStream byteArrayOutputStream = null;
        InputStream in = null;
        try{
            byteArrayOutputStream = QrCodeUtil.generateQrcode(url);
            in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if (byteArrayOutputStream!=null){
                    byteArrayOutputStream.close();
                }
                if (in !=null){
                    in.close();
                }
            }catch (Exception e){
                System.out.println("colose error!");
            }

        }
        Image image = new Image(in);
        return new ImageView(image);
    }

    /**
     * 手机号+验证码发送功能登录
     */
    public void createUserAndPwdPane(){
        currentGridPane.getChildren().clear();
        //用户名密码输入框
        HBox userNameHBox = creatInput(1,"请输入手机号","resouces/img/icon/phone.png");
        currentGridPane.add(userNameHBox,0,0,2,1);

        HBox passHBox = creatInput(3,"获取短信验证码", "/img/icon/ipass.png");
        currentGridPane.add(passHBox,0,1,2,1);

        //海外手机号
        HBox authHBox = creatHaiwaiInput();
        currentGridPane.add(authHBox,0,2,2,1);

        Button loginButton = creatButton("登录/注册");
        currentGridPane.add(loginButton,0,3,2,1);

        //登录事件，校验手机的验证码
        loginButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
              OnSuccessView on = new OnSuccessView();
              on.show(currentStage,"1","1");
            }
        });
        //其它登录标签
        HBox otherLoginHbox = creatOtherLoginBox("其它方式登录");
        currentGridPane.add(otherLoginHbox,0,4,2,1);

        //其它登录标签-qq、微信、微博icon排列
        List<String> iconPaths = Arrays.asList("/img/icon/iqq.jpg", "/img/icon/iwechat.jpg", "/img/icon/iweibo.png");
        HBox iconBox = creatIconHBox(iconPaths);
        currentGridPane.add(iconBox,0,5,2,1);

        //协议引导
        Text tex = creatControctContent();
        currentGridPane.add(tex,0,6,2,1);

        GridPane.setMargin(userNameHBox,new Insets(15,0,0,0));
        GridPane.setMargin(passHBox,new Insets(15,0,0,0));
        GridPane.setMargin(authHBox,new Insets(10,0,0,0));
        GridPane.setMargin(loginButton,new Insets(25,0,0,0));
        GridPane.setMargin(otherLoginHbox,new Insets(20,0,0,0));
        GridPane.setMargin(iconBox,new Insets(20,0,0,0));
        GridPane.setMargin(tex,new Insets(20,0,0,0));
    }

    public void createAuthCodePane(){
        currentGridPane.getChildren().clear();
        //用户名密码输入框
        HBox userNameHBox = creatInput(1,"请输入用户名或者邮箱","/img/icon/iemail.png");
        currentGridPane.add(userNameHBox,0,0,2,1);

        HBox passHBox = creatInput(2,"请输入密码", "/img/icon/ipass.png");
        currentGridPane.add(passHBox,0,1,2,1);

        HBox authHBox = creatInput(4,"请输入右侧的验证码","/img/icon/auth-icon.png");
        currentGridPane.add(authHBox,0,2,2,1);

        Button loginButton = creatButton("登录");
        currentGridPane.add(loginButton,0,3,2,1);
        loginButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {

            }
        });

        //其它登录标签
        HBox otherLoginHbox = creatOtherLoginBox("其它方式登录");
        currentGridPane.add(otherLoginHbox,0,4,2,1);

        //其它登录标签-qq、微信、微博icon排列
        List<String> iconPaths = Arrays.asList("/img/icon/iqq.jpg", "/img/icon/iwechat.jpg", "/img/icon/iweibo.png");
        HBox iconBox = creatIconHBox(iconPaths);
        currentGridPane.add(iconBox,0,5,2,1);

        //协议引导
        Text tex = creatControctContent();
        currentGridPane.add(tex,0,6,2,1);

        GridPane.setMargin(userNameHBox,new Insets(15,0,0,0));
        GridPane.setMargin(passHBox,new Insets(15,0,0,0));
        GridPane.setMargin(authHBox,new Insets(15,0,0,0));
        GridPane.setMargin(loginButton,new Insets(25,0,0,0));
        GridPane.setMargin(otherLoginHbox,new Insets(20,0,0,0));
        GridPane.setMargin(iconBox,new Insets(20,0,0,0));
        GridPane.setMargin(tex,new Insets(20,0,0,0));
    }


    /**
     * 创建带icon图标的TextFied
     * @return
     */
    private static  HBox creatInput(int type,String preText,String icon){

        int imgWeight = 25;
        int imgHeight = 25;
        String labelStyle = "-fx-background-color: white; -fx-padding: 0 0 5 0; -fx-text-fill: gray; fx-border-style: solid; -fx-border-width: 0 0 1 0; -fx-border-color: #c7c2c2";
        HBox hBox = new HBox();
        Image img = null;
        ImageView imageView = new ImageView();
        imageView.setFitWidth(imgWeight);
        imageView.setFitHeight(imgHeight);
        if (type==1){
            //用户名input
            TextField t = new TextField();
            t.setPrefWidth(putWeight);
            t.setPrefHeight(putHeight);
            t.setPromptText(preText);
            t.setStyle(labelStyle);
            hBox.getChildren().add(t);
            String s = new File(icon).toURI().toString();
            img = new Image(s);
        }else if (type==2){
            PasswordField passwordField = new PasswordField();
            passwordField.setPromptText(preText);
            passwordField.setPrefWidth(putWeight);
            passwordField.setPrefHeight(putHeight);
            passwordField.setStyle(labelStyle);
            hBox.getChildren().add(passwordField);
            String s = new File(icon).toURI().toString();
            img = new Image(s);
        }else if (type==3){
        //短信验证码右边icon位置不是imgView，是个文字连接可用lable，触发后进行倒计时60s处理
            TextField t = new TextField();
            t.setPrefWidth(putWeight);
            t.setPrefHeight(putHeight);
            t.setPromptText(preText);
            t.setStyle(labelStyle);
            hBox.getChildren().add(t);

            //默认是蓝色，鼠标移入变灰，移出变蓝，点击触发倒计时，字体灰色
            Label label = new Label("发送验证码");
            label.setTextFill(Color.rgb(4,97,207));// 蓝色
            label.setOnMouseClicked(new EventHandler<MouseEvent>() {

                @Override
                public void handle(MouseEvent event) {
                    authCode = AuthCodeUtils.getRandom(6);
                    new Thread(()->{
                        AtomicInteger time = new AtomicInteger(60);

                        while (time.get()>0){
                            try {
                                TimeUnit.SECONDS.sleep(1);
                                Platform.runLater(()->{
                                    int andDecrement = time.getAndDecrement();
                                    if (andDecrement!=0){
                                        label.setText("有 效 期"+andDecrement+"s");
                                        label.setTextFill(Color.rgb(190,190,198)); //灰色
                                    }else {
                                        label.setText("发送验证码");
                                        label.setTextFill(Color.rgb(4,97,207));// 蓝色
                                    }

                                });
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    t.setText(authCode);
                }
            });

            label.setOnMouseEntered(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    label.setTextFill(Color.rgb(190,190,198)); //灰色
                }
            });

            label.setOnMouseExited(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    label.setTextFill(Color.rgb(4,97,207));// 蓝色
                }
            });

            hBox.getChildren().add(label);
            HBox.setMargin(label,new Insets(0,0,0,-60));
            return hBox;
        }else {
            TextField t = new TextField();
            t.setPrefWidth(210);
            t.setPrefHeight(putHeight);
            t.setPromptText(preText);
            t.setStyle(labelStyle);
            hBox.getChildren().add(t);
            String aucode = AuthCodeUtils.getRandom(4);
            img = AuthCodeUtils.creatAuthCode(aucode);
            imageView.setFitWidth(putWeight-180);
            imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    String aucode = AuthCodeUtils.getRandom(4);
                    Image img = AuthCodeUtils.creatAuthCode(aucode);
                    imageView.setImage(img);
                }
            });
        }
        imageView.setImage(img);
        hBox.getChildren().add(imageView);
        //通过hbox的绝对定位将icon移动到TextFied上面去
        HBox.setMargin(imageView,new Insets(0,0,0,-20));
        return hBox;
    }

    private static  HBox creatHaiwaiInput(){
        Label lab1 = new Label("海外手机登录");
        lab1.setTextFill(Color.rgb(4,97,207));
        Label lab2 = new Label("忘记密码");
        lab2.setTextFill(Color.rgb(190,190,198));
        HBox hBox = new HBox();
        hBox.setStyle("-fx-font-size: 14");
        hBox.setSpacing(160);
        hBox.getChildren().addAll(lab1,lab2);
        return hBox;
    }


    private Button creatButton(String buttonName){
        Button button = new Button(buttonName);
        String buttonStyle = "-fx-background-color: #0461CFFF; -fx-border-radius: 5; -fx-text-fill: white; -fx-font-family: 'Arial'; -fx-font-size: 13";
        button.setAlignment(Pos.CENTER);
        button.setStyle(buttonStyle);
        button.setPrefWidth(putWeight);
        button.setPrefHeight(putHeight+5);
        return button;
    }

    private HBox creatOtherLoginBox(String name){
        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER_LEFT);
        hBox.setSpacing(15);
        Line line = new Line();
        line.setStartX(0);
        line.setEndX(100);
        line.setStartY(0);
        line.setEndY(0);
        line.setStroke(Color.rgb(190,190,198));
        line.setStrokeWidth(1);

        Line line2 = new Line();
        line2.setStartX(0);
        line2.setEndX(100);
        line2.setStartY(0);
        line2.setEndY(0);
        line2.setStroke(Color.rgb(190,190,198));
        line2.setStrokeWidth(1);

        Label l = new Label(name);
        String labelStyle = "-fx-font-size: 12; -fx-text-fill: #bebec6; -fx-background-color: white";
        l.setStyle(labelStyle);
        hBox.getChildren().addAll(line,l,line2);

        return hBox;
    }

    private HBox creatIconHBox(List<String> iconPaths){
        HBox hbox = new HBox();
        hbox.setAlignment(Pos.CENTER);
        hbox.setSpacing(70);
        int imgWeight = 30;
        int imgHeight = 30;
        for (String path : iconPaths){
            Image image = new Image(path);
            ImageView imageView = new ImageView(image);
            imageView.setFitHeight(imgHeight);
            imageView.setFitWidth(imgWeight);
            hbox.getChildren().add(imageView);
        }
        return hbox;
    }

    private Text creatControctContent(){
        String tStyle = "-fx-font-size: 12; -fx-background-color: white";
        Text text = new Text();
        text.setText("未注册手机验证后自动登录，注册即代表同意《知乎协议》《隐私保护指引》");
        text.setFill(Color.rgb(190,190,198));
        text.setStrokeWidth(300);
        text.setWrappingWidth(300);
        text.setStyle(tStyle);
        return text;
    }

}
